<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="modalTitle" @ok="onButtonOkClick">
    <div>
      <span style="color: rgb(149, 147, 147); margin-left: 1rem">
        注意：用于控制角色权限或其他权限使用。
      </span>
    </div>
    <BasicTree
      title="部门列表"
      toolbar
      search
      :clickRowToExpand="false"
      :checkable="true"
      :treeData="treeData"
      :onCheck="checkSelect"
      :checkedKeys="keys"
      :showLine="{ showLeafIcon: false }"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, inject, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  import { BasicTree, TreeItem } from '/@/components/Tree';

  import { getUserDeptsTree, setUserDepts } from '/@/api/project/user';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'setUserDepts',
    components: {
      BasicTree,
      BasicModal,
    },
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);
      const moduleName = inject<string>('moduleName');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');

      const dataId = ref('');
      const project = ref('');

      const treeData = ref<TreeItem[]>([]);

      //部门id集合
      const dids = ref<number[] | string[]>([]);
      //已经关联的key
      const keys = ref<number[] | string[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);

        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (data?.project) {
          project.value = data.project; //项目编码
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }

        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getDeptList();
      });

      /**
       * 获取部门树形结构数据
       */
      async function getDeptList() {
        getUserDeptsTree({ id: dataId.value, project: project.value })
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            treeData.value = res.nodes as unknown as TreeItem[];
            keys.value = res.checkedKeys;
            console.log('已经关联的key ', keys.value);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 获取选中的节点key
       */
      function checkSelect(checkedKeys) {
        console.log('勾选的节点key:', checkedKeys);
        dids.value = checkedKeys;
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          setUserDepts({ userid: dataId.value, project: project.value, dids: dids.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }
        // 清空选中的行;
        keys.value = [];
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        getDeptList,
        onButtonOkClick,
        treeData,
        checkSelect,
        keys,
      };
    },
  });
</script>
